<template>
  <div class="reports-container">
    <!-- 两列布局 -->
    <el-container>
      <!-- 左侧菜单 -->
      <el-aside width="200px">
        <div class="menu-header">
          <h3>报表中心</h3>
        </div>
        <el-menu
          :default-active="reportType"
          class="report-menu"
          @select="handleReportTypeChange"
        >
          <el-menu-item-group title="收银报表" class="menu-group">
            <el-menu-item index="daily-summary" class="menu-item">收银日报表</el-menu-item>
            <el-menu-item index="monthly-summary" class="menu-item">月度报表</el-menu-item>
            <el-menu-item index="yearly-summary" class="menu-item">年度报表</el-menu-item>
            <el-menu-item index="receipt-details" class="menu-item">收款明细表</el-menu-item>
          </el-menu-item-group>
          
          <el-menu-item-group title="销售分析" class="menu-group">
            <el-menu-item index="sales-overview" disabled class="menu-item disabled">销售概览</el-menu-item>
            <el-menu-item index="hourly-analysis" disabled class="menu-item disabled">时段分析</el-menu-item>
            <el-menu-item index="product-analysis" disabled class="menu-item disabled">商品分析</el-menu-item>
            <el-menu-item index="category-analysis" disabled class="menu-item disabled">分类分析</el-menu-item>
            <el-menu-item index="channel-analysis" disabled class="menu-item disabled">渠道分析</el-menu-item>
            <el-menu-item index="payment-analysis" disabled class="menu-item disabled">支付分析</el-menu-item>
          </el-menu-item-group>
          
          <el-menu-item-group title="财务报表" class="menu-group">
            <el-menu-item index="profit-loss" class="menu-item">损益表</el-menu-item>
            <el-menu-item index="income-statement" disabled class="menu-item disabled">收入报表</el-menu-item>
            <el-menu-item index="expense-statement" disabled class="menu-item disabled">费用报表</el-menu-item>
          </el-menu-item-group>
        </el-menu>
      </el-aside>
      
      <!-- 右侧内容区 -->
      <el-container class="main-content">
        <!-- 标题和查询条件区域 -->
        <el-header height="auto" class="compact-header">
          <div class="header-content">
            <div class="report-title">
              <h2>{{ getReportTitle }}</h2>
            </div>
            
            <div class="filter-container">
              <div class="filter-row">
                <div class="date-picker-section">
                  <el-form :inline="true" class="filter-form" size="small">
                    <el-form-item :label="getDateLabel">
                      <div class="date-picker-container">
                        <!-- 年报：年份选择器 -->
                        <el-date-picker
                          v-if="reportType === 'yearly-summary'"
                          v-model="selectedYear"
                          type="year"
                          placeholder="选择年份"
                          value-format="YYYY"
                          @change="handleYearChange"
                          size="small"
                        />

                        <!-- 月报：月份选择器 -->
                        <el-date-picker
                          v-else-if="reportType === 'monthly-summary'"
                          v-model="selectedMonth"
                          type="month"
                          placeholder="选择月份"
                          value-format="YYYY-MM"
                          @change="handleMonthChange"
                          size="small"
                        />

                        <!-- 日报和其他：日期范围选择器 -->
                        <el-date-picker
                          v-else
                          v-model="dateRange"
                          type="daterange"
                          range-separator="至"
                          start-placeholder="开始日期"
                          end-placeholder="结束日期"
                          value-format="YYYY-MM-DD"
                          @change="handleDateRangeChange"
                          size="small"
                        />
                      </div>
                    </el-form-item>
                  </el-form>
                </div>

                <div class="action-buttons">
                  <el-button type="primary" @click="refreshReport" :loading="loading" size="small">
                    <el-icon><Search /></el-icon> 查询
                  </el-button>

                  <el-button type="primary" @click="printReport" :disabled="!hasReportData" size="small">
                    <el-icon><Printer /></el-icon> 打印
                  </el-button>

                  <el-dropdown @command="handleExport" trigger="click">
                    <el-button type="success" size="small">
                      <el-icon><Download /></el-icon> 导出
                      <el-icon class="el-icon--right"><ArrowDown /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="excel">导出Excel</el-dropdown-item>
                        <el-dropdown-item command="pdf">导出PDF</el-dropdown-item>
                        <el-dropdown-item command="csv">导出CSV</el-dropdown-item>
                        <el-dropdown-item command="enhanced" divided>美化版Excel</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </div>
          </div>
        </el-header>
        
        <!-- 报表内容区域 -->
        <el-main class="report-content">
          <!-- 加载状态 -->
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="15" animated />
          </div>
          
          <!-- 报表内容 -->
          <template v-else>
            <!-- 根据报表类型动态加载不同的报表组件 -->
            <component
              v-if="!reportData.message && currentReportComponent"
              :is="currentReportComponent"
              :date-range="dateRange"
              :loading="loading"
              :report-data="reportData"
              :key="reportType"
              @refresh="handleComponentRefresh"
            />
            
            <!-- 显示API返回的消息 -->
            <div v-else-if="reportData.message" class="empty-report">
              <el-empty :description="reportData.message">
                <el-button type="primary" size="small" @click="reportType = 'receipt-details'">查看收款明细表</el-button>
              </el-empty>
            </div>
            
            <!-- 占位组件：当没有选择报表类型时显示 -->
            <div v-else class="empty-report">
              <el-empty description="请选择报表类型查看分析数据">
                <el-button type="primary" size="small" @click="reportType = 'receipt-details'">查看收款明细表</el-button>
              </el-empty>
            </div>
          </template>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, markRaw, watch } from 'vue';
import { Search, Printer, Download, ArrowDown } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import reportApi, { getMonthlyReport, getYearlyReport } from '@/api/reports';
import { exportToExcel, printContent } from '@/utils/exportUtils';

// 静态导入报表组件
import ProfitLossStatement from './components/ProfitLossStatement.vue';
import ReceiptDetails from './components/ReceiptDetails.vue';
import DailySummary from './components/DailySummary.vue';
import MonthlySummary from './components/MonthlySummary.vue';
import YearlySummary from './components/YearlySummary.vue';
// TODO: 导入其他报表组件
// const SalesOverview = markRaw(() => import('./components/SalesOverview.vue'));
// const HourlyAnalysis = markRaw(() => import('./components/HourlyAnalysis.vue'));
// const ProductAnalysis = markRaw(() => import('./components/ProductAnalysis.vue'));
// const CategoryAnalysis = markRaw(() => import('./components/CategoryAnalysis.vue'));
// const ChannelAnalysis = markRaw(() => import('./components/ChannelAnalysis.vue'));
// const PaymentAnalysis = markRaw(() => import('./components/PaymentAnalysis.vue'));

// 状态变量
const reportType = ref('receipt-details'); // 默认选择收款明细表
const dateRange = ref([]);
const selectedYear = ref(new Date().getFullYear().toString());
const selectedMonth = ref(new Date().toISOString().slice(0, 7)); // YYYY-MM格式
const loading = ref(false);
const reportData = ref({});
const componentParams = ref({});



// 计算属性 - 报表标题
const getReportTitle = computed(() => {
  const titles = {
    'daily-summary': '收银日报表',
    'monthly-summary': '月度报表',
    'yearly-summary': '年度报表',
    'receipt-details': '收款明细表',
    'sales-overview': '销售概览',
    'hourly-analysis': '时段分析',
    'product-analysis': '商品分析',
    'category-analysis': '分类分析',
    'channel-analysis': '渠道分析',
    'payment-analysis': '支付分析',
    'profit-loss': '损益表',
    'income-statement': '收入报表',
    'expense-statement': '费用报表'
  };

  return titles[reportType.value] || '报表中心';
});

// 计算属性 - 日期标签
const getDateLabel = computed(() => {
  const labels = {
    'yearly-summary': '年份:',
    'monthly-summary': '月份:',
    'daily-summary': '日期:',
    'receipt-details': '日期:'
  };

  return labels[reportType.value] || '日期:';
});

// 计算属性 - 是否有报表数据
const hasReportData = computed(() => {
  return Object.keys(reportData.value).length > 0;
});

// 根据选择的报表类型返回对应的组件
const currentReportComponent = computed(() => {
  console.log('计算currentReportComponent，当前报表类型:', reportType.value);
  
  let component = null;
  
  switch (reportType.value) {
    case 'profit-loss':
      component = markRaw(ProfitLossStatement);
      break;
    case 'receipt-details':
      component = markRaw(ReceiptDetails);
      break;
    case 'daily-summary':
      component = markRaw(DailySummary);
      break;
    case 'monthly-summary':
      component = markRaw(MonthlySummary);
      break;
    case 'yearly-summary':
      component = markRaw(YearlySummary);
      break;
    default:
      // 默认返回null
      component = null;
  }
  
  console.log('选择的组件:', component ? (component.__name || '未命名组件') : 'null');
  return component;
});

// 处理报表类型变更
const handleReportTypeChange = (key) => {
  // 检查是否为禁用的报表类型
  const disabledReportTypes = [
    'sales-overview', 'hourly-analysis', 'product-analysis',
    'category-analysis', 'channel-analysis', 'payment-analysis',
    'income-statement', 'expense-statement'
  ];
  
  if (disabledReportTypes.includes(key)) {
    ElMessage.info(`报表类型"${key}"尚未实现，请选择其他报表类型`);
    return;
  }
  
  reportType.value = key;
  
  // 清空组件参数
  componentParams.value = {};
  
  // 刷新报表数据
  refreshReport();
};

// 处理日期范围变更
const handleDateRangeChange = () => {
  refreshReport();
};

// 处理年份变化
const handleYearChange = (value) => {
  console.log('年份变化:', value);
  selectedYear.value = value;
  // 自动设置日期范围为整年
  if (value) {
    dateRange.value = [`${value}-01-01`, `${value}-12-31`];
    refreshReport();
  }
};

// 处理月份变化
const handleMonthChange = (value) => {
  console.log('月份变化:', value);
  selectedMonth.value = value;
  // 自动设置日期范围为整月
  if (value) {
    const [year, month] = value.split('-');
    const startDate = `${year}-${month}-01`;
    const endDate = new Date(parseInt(year), parseInt(month), 0).toISOString().split('T')[0];
    dateRange.value = [startDate, endDate];
    refreshReport();
  }
};

// 处理组件刷新请求
const handleComponentRefresh = (params) => {
  // 保存组件传递的参数
  componentParams.value = params || {};
  
  // 刷新报表
  refreshReport();
};

// 刷新报表数据
const refreshReport = async () => {
  if (!reportType.value) {
    ElMessage.warning('请选择报表类型');
    return;
  }

  // 根据报表类型验证日期参数
  if (reportType.value === 'yearly-summary') {
    if (!selectedYear.value) {
      ElMessage.warning('请选择年份');
      return;
    }
  } else if (reportType.value === 'monthly-summary') {
    if (!selectedMonth.value) {
      ElMessage.warning('请选择月份');
      return;
    }
  } else {
    if (!dateRange.value || dateRange.value.length !== 2) {
      ElMessage.warning('请选择日期范围');
      return;
    }
  }
  
  // 检查是否为禁用的报表类型
  const disabledReportTypes = [
    'sales-overview', 'hourly-analysis', 'product-analysis',
    'category-analysis', 'channel-analysis', 'payment-analysis',
    'income-statement', 'expense-statement'
  ];
  
  if (disabledReportTypes.includes(reportType.value)) {
    reportData.value = { message: `报表类型"${getReportTitle}"尚未实现，请选择其他报表类型` };
    return;
  }
  
  loading.value = true;
  
  try {
    const [startDate, endDate] = dateRange.value;
    let response;
    
    // 根据报表类型调用不同的API
    switch (reportType.value) {
      case 'profit-loss':
        const { periodType = 'monthly', comparisonType = 'previous' } = componentParams.value;
        response = await reportApi.getProfitLossStatement(startDate, endDate, periodType, comparisonType);
        break;
      
      case 'receipt-details':
        response = await reportApi.getReportData('receipt-details', startDate, endDate, {
          ...componentParams.value
        });
        break;
      
      case 'daily-summary':
        console.log('正在获取收银日报表数据...', startDate, endDate);
        try {
          // 日报只查询单日数据，如果是日期范围，取开始日期
          const reportDate = startDate;
          response = await reportApi.getReportData('daily-summary', reportDate, reportDate, {
            ...componentParams.value
          });
          console.log('收银日报表原始响应:', response);
          if (response && response.data && response.data.status === 'success') {
            console.log('收银日报表数据已获取:', response.data.data);
          } else {
            console.error('收银日报表响应格式异常:', response);
          }
        } catch (error) {
          console.error('获取收银日报表时出错:', error);
          throw error;
        }
        break;

      case 'monthly-summary':
        console.log('正在获取月度报表数据...', startDate, endDate);
        try {
          // 从日期范围中提取年月信息
          const date = new Date(startDate);
          const year = date.getFullYear();
          const month = date.getMonth() + 1;
          console.log('提取的年月信息:', { year, month, startDate, selectedMonth: selectedMonth.value });
          response = await getMonthlyReport(year, month);
          console.log('月度报表原始响应:', response);
        } catch (error) {
          console.error('获取月度报表时出错:', error);
          throw error;
        }
        break;

      case 'yearly-summary':
        console.log('正在获取年度报表数据...', startDate, endDate);
        try {
          // 从日期范围中提取年份信息
          const date = new Date(startDate);
          const year = date.getFullYear();
          response = await getYearlyReport(year);
          console.log('年度报表原始响应:', response);
        } catch (error) {
          console.error('获取年度报表时出错:', error);
          throw error;
        }
        break;
      
      default:
        // 对于未实现的报表类型，显示提示信息
        reportData.value = { message: `报表类型"${reportType.value}"尚未实现，请选择其他报表类型` };
        loading.value = false;
        return;
    }
    
    // 检查响应数据
    if (response && response.data) {
      if (response.data.status === 'success') {
        if (response.data.data) {
          reportData.value = response.data.data;
          console.log('报表数据已更新:', reportData.value);
        } else if (response.data.message) {
          ElMessage.info(response.data.message);
          reportData.value = { message: response.data.message };
        } else {
          throw new Error('响应数据格式异常');
        }
      } else if (response.data.data && response.data.data.error) {
        // 处理API返回的错误
        throw new Error(response.data.data.message || '获取报表数据失败');
      } else if (response.data.message) {
        // 处理API返回的消息
        ElMessage.info(response.data.message);
        reportData.value = { message: response.data.message };
      } else {
        throw new Error(response.data.message || '获取报表数据失败');
      }
    } else {
      throw new Error(response?.data?.message || '获取报表数据失败');
    }
  } catch (error) {
    console.error('获取报表数据失败:', error);
    ElMessage.error(`获取报表数据失败: ${error.message}`);
    
    // 清空报表数据
    reportData.value = {};
  } finally {
    loading.value = false;
  }
};

// 处理导出
const handleExport = async (format) => {
  if (!reportType.value || !dateRange.value || dateRange.value.length !== 2) {
    ElMessage.warning('请选择报表类型和日期范围');
    return;
  }
  
  try {
    let [startDate, endDate] = dateRange.value;

    // 确保日期格式为字符串
    console.log('导出报表使用的日期范围(原始):', { startDate, endDate });

    // 如果是日期对象，转换为YYYY-MM-DD格式的字符串
    if (startDate instanceof Date) {
      startDate = startDate.toISOString().split('T')[0];
    }

    if (endDate instanceof Date) {
      endDate = endDate.toISOString().split('T')[0];
    }
    
    console.log('导出报表使用的日期范围(处理后):', { startDate, endDate });
    
    // 显示导出中提示
    const loadingMessage = ElMessage({
      message: '正在导出报表，请稍候...',
      type: 'info',
      duration: 0
    });
    
    // 调用导出API
    switch (reportType.value) {
      case 'profit-loss':
        const { periodType = 'monthly' } = componentParams.value;
        await reportApi.exportProfitLossStatement(startDate, endDate, periodType, format);
        break;
      
      case 'receipt-details':
        await reportApi.exportReport('receipt-details', startDate, endDate, format, {
          ...componentParams.value
        });
        break;
      
      case 'daily-summary':
        if (format === 'enhanced') {
          // 导出美化版Excel
          console.log('调用美化版导出API，参数:', { startDate, endDate });
          await reportApi.exportEnhancedDailyRangeReport(startDate, endDate);
        } else {
          // 导出普通Excel
          await reportApi.exportReport('daily-summary', startDate, endDate, format, {
            ...componentParams.value
          });
        }
        break;
      
      default:
        // 关闭导出中提示
        loadingMessage.close();
        ElMessage.warning(`报表类型"${reportType.value}"尚未实现导出功能`);
        return;
    }
    
    // 关闭导出中提示
    loadingMessage.close();
    
    ElMessage.success('报表导出成功');
  } catch (error) {
    console.error('导出报表失败:', error);
    ElMessage.error(`导出报表失败: ${error.message}`);
  }
};

// 打印报表
const printReport = () => {
  if (!hasReportData.value) {
    ElMessage.warning('没有可打印的报表数据');
    return;
  }
  
  // 根据报表类型调用不同的打印处理
  switch (reportType.value) {
    case 'receipt-details':
      // 生成收款明细表打印内容
      const printTitle = `收款明细表 (${dateRange.value[0]} 至 ${dateRange.value[1]})`;
      const printContent = generateReceiptDetailsPrintContent();
      printContent(printContent, printTitle);
      break;
    
    // 其他报表类型
    default:
      ElMessage.info('正在准备打印...');
      // 调用对应组件的打印方法
      if (currentReportComponent.value) {
        // 通过事件调用子组件的打印方法
        // 此处假设子组件暴露了print方法
        // 实际实现可能需要调整
      }
  }
};

// 生成收款明细表打印内容
const generateReceiptDetailsPrintContent = () => {
  // 实际项目中，这里应该从reportData.value生成打印内容HTML
  return `
    <div class="print-header">
      <h1>收款明细表</h1>
      <p>日期范围: ${dateRange.value[0]} 至 ${dateRange.value[1]}</p>
    </div>
    <table class="print-table">
      <thead>
        <tr>
          <th>单号</th>
          <th>日期</th>
          <th>金额</th>
          <th>收款方式</th>
          <th>操作员</th>
        </tr>
      </thead>
      <tbody>
        <!-- 这里应该是实际的报表数据 -->
      </tbody>
    </table>
  `;
};

// 组件挂载时初始化
onMounted(() => {
  // 初始化日期范围
  const today = new Date();
  const endDateStr = today.toISOString().split('T')[0]; // 今天
  
  const startDate = new Date();
  startDate.setDate(startDate.getDate() - 30); // 30天前
  const startDateStr = startDate.toISOString().split('T')[0];
  
  dateRange.value = [startDateStr, endDateStr];

  // 初始化报表
  refreshReport();
});

// 监听reportType变化
watch(reportType, (newType) => {
  console.log('报表类型变更为:', newType);
  console.log('将使用组件:', currentReportComponent.value ? currentReportComponent.value.name : 'null');

  // 当切换到月报时，自动设置当前月份的日期范围
  if (newType === 'monthly-summary' && selectedMonth.value) {
    const [year, month] = selectedMonth.value.split('-');
    const startDate = `${year}-${month}-01`;
    const endDate = new Date(parseInt(year), parseInt(month), 0).toISOString().split('T')[0];
    dateRange.value = [startDate, endDate];
    console.log('自动设置月报日期范围:', dateRange.value);
  }

  // 当切换到年报时，自动设置当前年份的日期范围
  if (newType === 'yearly-summary' && selectedYear.value) {
    const year = selectedYear.value;
    const startDate = `${year}-01-01`;
    const endDate = `${year}-12-31`;
    dateRange.value = [startDate, endDate];
    console.log('自动设置年报日期范围:', dateRange.value);
  }
});

// 监听组件参数变化
watch(componentParams, () => {
  refreshReport();
}, { deep: true });


</script>

<style scoped>
.reports-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.el-container {
  height: 100%;
}

.main-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.menu-header {
  height: 50px;
  line-height: 50px;
  text-align: center;
  background-color: #f5f7fa;
  color: #303133;
  border-bottom: 1px solid #e6e6e6;
}

.menu-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: bold;
}

.report-menu {
  height: calc(100% - 50px);
  border-right: 1px solid #e6e6e6;
}

/* 菜单样式 */
.menu-group {
  margin-top: 5px;
}

.menu-item {
  color: #303133;
  height: 36px;
  line-height: 36px;
  font-size: 13px;
}

.menu-item.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 深度选择器样式 */
:deep(.el-menu-item-group__title) {
  color: #606266;
  padding-left: 16px;
  font-size: 12px;
  font-weight: bold;
  padding-top: 8px;
  padding-bottom: 4px;
}

/* 菜单项的悬停和激活效果 */
:deep(.el-menu-item:not(.is-disabled):hover),
:deep(.el-menu-item.is-active) {
  background-color: #ecf5ff;
  color: #409EFF;
}

.el-aside {
  background-color: #ffffff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.compact-header {
  padding: 0;
  background-color: #f5f7fa;
  border-bottom: 1px solid #e6e6e6;
}

.header-content {
  padding: 8px 16px;
}

.report-title {
  margin-bottom: 8px;
}

.report-title h2 {
  margin: 0;
  font-size: 16px;
  color: #303133;
  font-weight: 500;
}

.filter-container {
  background-color: #ffffff;
  padding: 12px 16px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.filter-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 16px;
}

.date-picker-section {
  flex: 1;
  display: flex;
  align-items: center;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.form-item-container,
.date-picker-container {
  display: flex;
  align-items: center;
}

.form-item-container {
  width: 120px;
}

.date-picker-container {
  width: 240px;
}

:deep(.el-form-item) {
  margin-bottom: 0;
  margin-right: 8px;
  display: flex;
  align-items: center;
}

:deep(.el-form-item__label) {
  line-height: 32px;
  padding-right: 6px;
}

:deep(.el-form-item__content) {
  display: flex;
  align-items: center;
  flex: 1;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-input__wrapper),
:deep(.el-select__wrapper) {
  width: 100%;
}

.action-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.report-content {
  padding: 16px;
  background-color: #f5f7fa;
  overflow-y: auto;
  flex: 1;
}

.loading-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.empty-report {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
}

@media screen and (max-width: 768px) {
  .el-aside {
    width: 64px !important;
  }

  .filter-row {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .date-picker-section {
    width: 100%;
  }

  .filter-form {
    width: 100%;
  }

  .filter-form .el-form-item {
    margin-right: 0;
    width: 100%;
  }

  .action-buttons {
    justify-content: center;
    flex-wrap: wrap;
  }
}

/* 自定义滚动条样式 */
:deep(::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

:deep(::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 4px;
}

:deep(::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}

:deep(.el-date-editor.el-input) {
  width: 100%;
}

:deep(.el-date-editor--daterange) {
  width: 100% !important;
}
</style> 